package com.init.engineering.controller;

import com.init.engineering.pages.PageResult;
import com.init.engineering.pages.QueryPageBean;
import com.init.engineering.pages.Result;
import com.init.engineering.pojo.Item;
import com.init.engineering.pojo.Subitem;
import com.init.engineering.service.ItemService;
import com.init.engineering.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private ItemService itemService;

    @PostMapping("/all")
    public PageResult findItemsByPages(@RequestBody QueryPageBean queryPageBean){
        PageResult stagesByPage = itemService.findItemsByPage(queryPageBean);
        return stagesByPage;
    }


    @PostMapping("/add")
    public Result addItem(@RequestBody Item item){

        //随机ID
        item.setIid(UUIDUtil.GetID());
        //获取系统更新时间
        item.setUpdatetime(new Date());
        int row = itemService.saveItem(item);
        Result result = new Result();
        if(row > 0){
            result.setMessage("添加成功");
            result.setFlag(true);
        }else{
            result.setFlag(false);
            result.setMessage("添加失败，请重试");
        }
        return result;
    }


    @GetMapping("/delete/{iid}")
    public Result deleteItem(@PathVariable("iid") String iid){
        int row = itemService.deleteItem(iid);
        Result result = new Result();
        if(row > 0){
            result.setMessage("删除成功");
            result.setFlag(true);
        }else{
            result.setFlag(false);
            result.setMessage("删除失败，请重试");
        }
        return result;
    }


    @GetMapping("/finditemByIid")
    public Result findItemByIid(String iid){
        Item item = itemService.findItemByIid(iid);
        Result result = new Result();
        if (item != null){
            result.setFlag(true);
            result.setMessage("回显成功");
            result.setData(item);
        }else{
            result.setFlag(false);
            result.setMessage("数据回显失败");
        }
        return result;
    }


    @PostMapping("/update")
    public Result updateItem(@RequestBody Item item){
        item.setUpdatetime(new Date());
        int row = itemService.updateItem(item);
        Result result = new Result();
        if(row > 0){
            result.setMessage("更新成功");
            result.setFlag(true);
        }else{
            result.setFlag(false);
            result.setMessage("更新失败，请重试");
        }
        return result;
    }

    @RequestMapping("/findItems")
    public Result findItems(){
        List<Item> items = itemService.findItems();
        Result result = new Result();
        if(items != null){
            result.setData(items);
            result.setFlag(true);
        }else{
            result.setFlag(false);
        }
        return result;
    }
}
